import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:animated_tree_view/animated_tree_view.dart' as treeview;
import 'package:yuellyfactory/util/MathUtil.dart';
import 'package:yuellyfactory/util/ToastUtil.dart';
import '../../components/NoScrollbarBehavior.dart';
import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ViewUtil.dart';
import '../../util/XNumberTextInputFormatter.dart';
import '../dto/PricePart.dart';


class TypeConfigVC extends StatefulWidget {
  final PricePart pricePart;
  final PricePart typePart;
  final Function callback;
  const TypeConfigVC({super.key, required this.pricePart,required this.typePart, required this.callback});

  @override
  State<TypeConfigVC> createState() => _TypeConfigVCState();
}

class _TypeConfigVCState extends State<TypeConfigVC> {

  List allDatas=[];
  treeview.TreeViewController? _controller;
  var sampleTree = treeview.TreeNode.root();

  PricePart selectPricePart=PricePart();
  List hasSelect=[];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initSelectData();
    getAllData();
  }


  @override
  Widget build(BuildContext context) {
    return ShadSheet(
      onClosing: () {
        debugPrint("关闭回调");
        widget.callback();
      },
      constraints:  BoxConstraints(minWidth: 800, maxWidth: 800,maxHeight: ViewUtil.matchHeight(context)-100,minHeight: ViewUtil.matchHeight(context)-100),
      title: Row(children: [
        const Text('分类可选配置'),
        const SizedBox(width: 50,),
        ViewUtil.doneIcon("保存配置", (){
          submit();
        })
      ],),
      child:
      Container(
        child:  ClipRRect(
          child: ShadResizablePanelGroup(
            children: [
              ShadResizablePanel(
                defaultSize: .3,
                minSize: .1,
                maxSize: .5,
                child:
                Card(
                    color: Colors.white,
                    child:Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        SizedBox(height: ViewUtil.screenHeight(10),),

                        // SizedBox(height: ViewUtil.screenHeight(10),),
                        Expanded(child:
                        treeview.TreeView.simple(
                            showRootNode: false,
                            focusToNewNode: false,
                            expansionIndicatorBuilder: (context, node) {
                              return treeview.ChevronIndicator.rightDown(
                                  tree: node,
                                  alignment: Alignment.centerRight,
                                  //color: Colors.grey[700],
                                  color:ColorUtil.colorBlue
                              );
                            },
                            indentation: const treeview.Indentation(
                                style: treeview.IndentStyle.roundJoint),
                            onItemTap: (item) {
                              print("Item tapped: ${item.key}");
                              selectPricePart=item.data;
                              setState(() {

                              });
                            },
                            onTreeReady: (controller) {
                              _controller = controller;
                            },
                            builder: (context, node) =>  Container(
                              decoration: BoxDecoration(
                                color: selectPricePart.id==node.key ? Colors.blue.withOpacity(0.1) : null,
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: ListTile(
                                title: Text("${node.data.name}"),

                              ),
                            ),
                            tree: sampleTree),)

                      ],
                    )

                ),
              ),
              ShadResizablePanel(
                defaultSize: .7,
                child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Card( color: Colors.white,
                        child:
                        ScrollConfiguration(
                          behavior: NoScrollbarBehavior(),
                          child: SingleChildScrollView(
                            child:
                            Padding(
                              padding: const EdgeInsets.all(5.0),
                              child:
                              Column(

                                children: [
                                  SizedBox(height: ViewUtil.screenWidth(10),),
                                  Row(
                                    children: [
                                      SizedBox(width: ViewUtil.screenWidth(10),),
                                      Expanded(child: Text(selectPricePart.name,
                                        style: TextStyle(fontSize: ViewUtil.fontSize(30),fontWeight: FontWeight.bold)
                                        ,),),

                                    ],
                                  ),
                                  if(selectPricePart.type=='serial')
                                    allPartWidgets()
                                ],
                              )


                              ,
                            ),),
                        ),

                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),


      ),
    );
  }





  void getAllData(){
    BaseRequest.postHttp("price/getmaterialfromtype",parameters: {"typeId":widget.typePart.id}, canTip: true , context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        List allParts=[];
        for(var i=0;i<datas.length;i++){
          var item=datas[i];
          var part=PricePart.fromJson(item);
          allParts.add(part);
        }
        allDatas=allParts;
        initTreeDatas(allParts);
      }


    }, onError: (error){

    });
  }

  void initTreeDatas(List allParts){
    var trees=treeview.TreeNode.root();
    for(PricePart brand in allParts){

      brand.path="${brand.id}";
      treeview.TreeNode brandNode=treeview.TreeNode(key: brand.id,data: brand);

      for(PricePart serial in brand.materialList){

        serial.path="${brand.id}.${serial.id}";
        treeview.TreeNode serialNode=treeview.TreeNode(key: serial.id,data: serial);

        for(PricePart part in serial.materialList){
          if(hasSelect.contains(part.id)){
            part.select=true;
          }else{
            part.select=false;
          }
        }
        brandNode.add(serialNode);
      }
      trees.add(brandNode);
    }
    sampleTree=trees;
    setState(() {

    });



  }

  Widget allPartWidgets(){

    List<Widget> views=[];
    for(PricePart part in selectPricePart.materialList){
      views.add(SizedBox(height: ViewUtil.screenHeight(10),));
      views.add(Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          FlutterSwitch(value: part.select,
              width: 40.0,
              height: 25.0,
              onToggle: (value){
                part.select=value;
                setState(() {

                });
              }),
          SizedBox(width: ViewUtil.screenWidth(10),),
          Text(part.name),
          Expanded(child: Container()),
        ],

      ));

      views.add(ViewUtil.lineView());
    }
    return Column(
      children: views,
    );
  }


  void initSelectData(){
    if(widget.pricePart.selectConfig.isNotEmpty){
      var config= jsonDecode(widget.pricePart.selectConfig);
      for(var item in config){
        var id=item["id"];
        if(id==widget.typePart.id){
          var value=item["value"];
          var list=jsonDecode(value);
          for(var material in list){
            hasSelect.add(material);
          }
        }
      }
    }
  }

  submit(){

    List selects=[];
    for(var brand in allDatas){
      for(var serial in brand.materialList){
        for(var part in serial.materialList){
          if(part.select){
            selects.add(part.id);
          }
        }
      }
    }



      if(selects.isEmpty){
        ToastUtil.showToast("请选择型号");
        return;
      }
      var datas={"id":widget.typePart.id,"value":selects};

      List newList=[];
      if(widget.pricePart.selectConfig.isNotEmpty){
        var config= jsonDecode(widget.pricePart.selectConfig);
        for(var item in config){
          var id=item["id"];
          if(id!=widget.typePart.id){
            var value=item["value"];
            var list=jsonDecode(value);
            newList.add({"id":id,"value":list});
          }
        }
      }
      newList.add(datas);

      var parm={
        "modelId":widget.pricePart.id,
        "selectConfig":newList,
      };
      BaseRequest.postHttp("price/modelconfig",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
        }
        Navigator.pop(context);
      }, onError: (error){

      });

  }
}
